import { asyncRoutes, constantRoutes } from '@/router'

// 模拟后端只返回拥有的菜单的path
const menu = ['/form/index','/example/table']

/**
 * 根据后端返回的path 匹配
 * @param route
 * @param parentPath
 */
function hasPermission(route, parentPath) {
  // console.log(route,parentPath)
  let newVar = parentPath ? parentPath + route.path : route.path
  if (route.children && route.children.length > 0) {
    for (let i = 0; i < menu.length; i++) {
      if (menu[i].startsWith(route.path)) {
        return true
      }
    }
    return false
  } else {
    // console.log(newVar,menu.includes(newVar))
    return menu.includes(newVar)
  }
}

export function filterAsyncRoutes(routes,  parentPath) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission( tmp, parentPath)) {
      if (tmp.children) {
        let newVar = parentPath ? parentPath + tmp.path : tmp.path
        tmp.children = filterAsyncRoutes(tmp.children, newVar)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, null)
        // console.log(accessedRoutes)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
